package com.example.hotel_lxy.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.MoreyBean;
import com.example.hotel_lxy.bean.StatementBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.dialog.ImageDialog;
import com.example.hotel_lxy.ui.dialog.TwoStatementDialog;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.google.gson.Gson;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 结单
 **/
@Route(path = "/main/StatementActivity")
public class StatementActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.back)
    ImageView back;
    @Autowired
    String id;
    @BindView(R.id.Rv_statement)
    RecyclerView RvStatement;
    @BindView(R.id.text_count)
    TextView textCount;
    @BindView(R.id.line_add)
    LinearLayout lineAdd;
    @BindView(R.id.img_add_view)
    ImageView imgAddView;
    @BindView(R.id.edit_office)
    EditText editOffice;
    @BindView(R.id.text_office_morey)
    TextView textOfficeMorey;
    @BindView(R.id.text_total)
    TextView textTotal;
    @BindView(R.id.edit_discount)
    EditText editDiscount;
    @BindView(R.id.text_balance)
    TextView textBalance;
    @BindView(R.id.text_determine)
    TextView textDetermine;
    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.d_money)
    TextView dMoney;
    private boolean aBoolean = false;
    private View view;
    private float morey;
    EditText edit_qt;//其他
    EditText edit_zs;//桌数
    private List<MoreyBean> mlist = new ArrayList<>();
    float j;//待付款
    float count;//已付款
    private String jsonString = "";
    private float cb;
    public static void start(String id) {
        ARouter.getInstance().build(ARouterPath.getStatementActivity())
                .withString("id", id)
                .navigation();
    }
    Handler handler = new Handler();
    Runnable runnable;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_statement;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

    }

    @Override
    public void doWork() {
        super.doWork();
        ARouter.getInstance().inject(this);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        textCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (aBoolean) {
                    aBoolean = false;
                    RvStatement.setVisibility(View.VISIBLE);

                } else {
                    RvStatement.setVisibility(View.GONE);
                    aBoolean = true;
                }
            }
        });
        imgAddView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showView();
            }
        });
        showView();
        showCheck();
        editOffice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().equals("")) {

                    return;
                }
                morey = Integer.valueOf(editable.toString()) * cb;
                String s = (Integer.valueOf(editable.toString()) * cb) + "";
                textOfficeMorey.setText("" + s + " 元");
                if (runnable != null) {
                    handler.removeCallbacks(runnable);
                }
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        //结束后进行操作
                        showData();
                    }
                };

                handler.postDelayed(runnable, 800);

            }
        });
        editDiscount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void afterTextChanged(Editable editable) {
                if (runnable != null) {
                    handler.removeCallbacks(runnable);
                }
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        //结束后进行操作
                        showData();
                    }
                };
                handler.postDelayed(runnable, 800);
            }
        });
        textDetermine.setOnClickListener(this);
    }

    private void showView() {
        view = LinearLayout.inflate(StatementActivity.this, R.layout.add_view, null);
        view.setTag(lineAdd.getChildCount());//设置标记
        initFind(view, lineAdd.getChildCount());
        view.setPadding(0, 10, 0, 0);
        lineAdd.addView(view);
    }

    private void initFind(View view, int childCount) {
        edit_qt = view.findViewById(R.id.edit_qt);//其他
        edit_zs = view.findViewById(R.id.edit_zs);//桌数
        edit_zs.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void afterTextChanged(Editable editable) {
                if (!editable.toString().equals("")) {
                    if (runnable != null) {
                        handler.removeCallbacks(runnable);
                    }
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            //结束后进行操作
                            showData();
                        }
                    };
                    handler.postDelayed(runnable, 800);
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showData() {
        mlist.clear();
        for (int j = 0; j < lineAdd.getChildCount(); j++) {
            View childAt = lineAdd.getChildAt(j);
            initFind(childAt, j);
            MoreyBean moreyBean = new MoreyBean();
            moreyBean.setTitle(edit_qt.getText().toString());
            if (!edit_zs.getText().toString().equals("")) {
                moreyBean.setMorey(edit_zs.getText().toString());
            } else {
                moreyBean.setMorey("0");
            }
            mlist.add(moreyBean);
        }
        String smoery = "0";
        for (int i = 0; i < mlist.size(); i++) {
            BigDecimal num = new BigDecimal(smoery);
            BigDecimal num1 =new BigDecimal(mlist.get(i).getMorey());
            smoery=num.add(num1)+"";
        }
//        mlist.stream().collect(Collectors.summingInt(MoreyBean::getMorey))
//        j = morey + smoery;
        BigDecimal num = new BigDecimal(morey);
        BigDecimal num1 =new BigDecimal(smoery);
        BigDecimal num6 =new BigDecimal(smoery);
        textTotal.setText("" +num.add(num1).setScale(2,BigDecimal.ROUND_HALF_UP));

        BigDecimal num2 = new BigDecimal(textTotal.getText().toString());
        BigDecimal num3 =new BigDecimal(count);
        String s= num2.subtract(num3).setScale(2,BigDecimal.ROUND_HALF_UP)+"";
        if (!editDiscount.getText().toString().equals("")) {
            BigDecimal num4 = new BigDecimal(s);
            BigDecimal num5 =new BigDecimal(editDiscount.getText().toString());
            textBalance.setText(num4.subtract(num5).setScale(2,BigDecimal.ROUND_HALF_UP) +"");
        } else {
            textBalance.setText(s + "");
        }

    }

    private void showCheck() {
        OkHttpUtils.post()
                .url(Api.POST_CHECK)
                .addHeader("flag", SPUtils.get(StatementActivity.this, "token", "").toString())
                .addParams("id", id + "")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "已付押金onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "已付押金onResponse   " + response);

                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            StatementBean statementBean = JsonUtils.parseByGson(response, StatementBean.class);
                            count = statementBean.getData().getCount();
                            textCount.setText("共 " + statementBean.getData().getCount() + " 元");
                            textTotal.setText(statementBean.getData().getCount() + "");
                            RvStatement.setLayoutManager(new LinearLayoutManager(StatementActivity.this));
                            dMoney.setText("X "+statementBean.getData().getD_money()+"元餐标 = ");
                            cb=Float.valueOf(statementBean.getData().getD_money());
                            editOffice.setText(""+statementBean.getData().getDesk());
                            RBaseAdapter<StatementBean.DataBean.ListBean> rBaseAdapter = new RBaseAdapter<StatementBean.DataBean.ListBean>(StatementActivity.this,
                                    R.layout.item_statemnt_info, statementBean.getData().getList()) {
                                @Override
                                protected void fillItem(RViewHolder holder, StatementBean.DataBean.ListBean item, int position) {
                                    TextView text_money = holder.itemView.findViewById(R.id.text_money);
                                    ImageView image = holder.itemView.findViewById(R.id.image);
                                    int i = position + 1;
                                    String d = DatePhotoUtils.numberToChinese(i);
                                    if (d.equals("一")) {
                                        text_money.setText("首次预付款     " + item.getMoney() + " 元     ");
                                    } else {
                                        text_money.setText(d + "次预付款     " + item.getMoney() + " 元     ");
                                    }
                                    Glide.with(StatementActivity.this).load(item.getImage()).into(image);
                                    image.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            ImageDialog.show(StatementActivity.this, null, item.getImage());
                                        }
                                    });
                                }

                                @Override
                                protected int getViewType(StatementBean.DataBean.ListBean item, int position) {
                                    return 0;
                                }
                            };
                            RvStatement.setAdapter(rBaseAdapter);
                        }
                        else if(beanBean.getCode().equals("4")){
                            SPUtils.put(StatementActivity.this,"token","");
                            Intent intent = new Intent(StatementActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                        else {
                            ToastUtils.shortToast(StatementActivity.this, beanBean.getMsg());
                            finish();
                        }

                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_determine:
                if (editOffice.getText().toString().equals("")) {
                    ToastUtils.show(StatementActivity.this, "桌数不能为空");
                    return;
                }
                Gson gson = new Gson();
                jsonString = gson.toJson(mlist);

                TwoStatementDialog.show(StatementActivity.this, null).setListener(new TwoStatementDialog.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String s) {
                        if (s.equals("1")) {
                            ShowDataDetermine();
                        }
                    }
                });

                break;
        }
    }

    private void ShowDataDetermine() {
        Log.e("TAG","flag   "+SPUtils.get(StatementActivity.this, "token", "").toString());
        Log.e("TAG","id   "+id);
        Log.e("TAG","desk   "+editOffice.getText().toString().trim().trim());
        Log.e("TAG","cou_money   "+textTotal.getText().toString().trim().trim());
        Log.e("TAG","discount_money   "+editDiscount.getText().toString().trim().trim());
        Log.e("TAG","final_money   "+textBalance.getText().toString().trim().trim());
        Log.e("TAG","content   "+content.getText().toString().trim().trim());
        Log.e("TAG","other   "+jsonString);
        OkHttpUtils.post()
                .url(Api.POST_CHECK_ORDER)
                .addHeader("flag", SPUtils.get(StatementActivity.this, "token", "").toString())
                .addParams("id", id)
                .addParams("desk", editOffice.getText().toString().trim().trim())
                .addParams("cou_money", textTotal.getText().toString().trim().trim())
                .addParams("discount_money", editDiscount.getText().toString().trim().trim())
                .addParams("final_money", textBalance.getText().toString().trim().trim())
                .addParams("content", content.getText().toString().trim().trim())
                .addParams("other", jsonString)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "确认结单onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "确认结单onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            ToastUtils.shortToast(StatementActivity.this,"结单"+beanBean.getMsg());
                            finish();
                        }else if(beanBean.getCode().equals("1")){
                            ToastUtils.shortToast(StatementActivity.this,""+beanBean.getMsg());
                        }
                        else if(beanBean.getCode().equals("4")){
                            SPUtils.put(StatementActivity.this,"token","");
                            Intent intent = new Intent(StatementActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                    }
                });
    }
}